<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="14">
          <el-button class="filter-item ml10" type="primary" :loading="downloadLoading" icon="el-icon-download" @click="exportExcel">导出</el-button>
          <el-button class="filter-item ml10" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="outClickFunc" icon="el-icon-edit">出库
          </el-button>
          <el-button class="filter-item ml10" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="editClickFunc" icon="el-icon-edit">库位调整
          </el-button>
        </el-col>
        <el-col :span="10" style="text-align: right">
          <el-input size="small" style="width: 200px" class="filter-item fsc-search" placeholder="车架号"
                    v-model="listQuery.condition.vin" @keyup.enter.native="searchClick"></el-input>
          <!--搜索-->
          <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-circle-plus-outline"
                     @click="moreSearch">更多
          </el-button>
          <el-dropdown trigger="click" :hide-on-click=false style="float: right;margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button class="filter-item" size="small" type="primary" v-waves>
                选择列
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-checkbox-group v-model="theadCheckVal">
                  <el-checkbox label="vin">车架号</el-checkbox>
                  <el-checkbox label="storeHouseId">仓库id</el-checkbox>
                  <el-checkbox label="locationNo">库位名称</el-checkbox>
                  <el-checkbox label="prepareStatus">状态</el-checkbox>
                  <el-checkbox label="materielId">车型</el-checkbox>
                  <el-checkbox label="inboundUser">入库用户</el-checkbox>
                  <el-checkbox label="inboundTime">入库时间</el-checkbox>
                  <el-checkbox label="storeHouseName">仓库名称</el-checkbox>
                </el-checkbox-group>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <div style="clean:both"></div>
    </div>
    <div v-show="searchFlag" style="height: auto;margin-top: 10px;">
      <el-form ref="form" :model="listQuery.condition" label-width="100px" :inline="true">
        <el-form-item label=车架号:>
          <el-input type="textarea" :rows="2" style="width: 250px"
                    v-model="listQuery.condition.vin"  placeholder="请输入车架号, 以逗号来分隔"></el-input>
          <!--<el-input placeholder="请输入车架号" class="w200" clearable v-model="listQuery.condition.vinNo"></el-input>-->
        </el-form-item>
        <el-form-item label="是否有入库指令">
          <el-select v-model="listQuery.condition.isShipment" placeholder="请选择状态">
            <el-option label="未选择" value=""></el-option>
            <el-option label="有" value="Y"></el-option>
            <el-option label="无" value="N"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库存转换状态">
          <el-select v-model="listQuery.condition.stockProperty" disabled placeholder="请选择状态">
            <el-option label="未选择" value=""></el-option>
            <el-option label="已转换" value="Y"></el-option>
            <el-option label="未转换" value="N"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="无单入库时间:">
          <el-date-picker class="w200" v-model="listQuery.condition.startDate" type="datetime" placeholder="选择日期时间"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          align="right" ></el-date-picker>
          <span class="zhi-font">至</span>
          <el-date-picker class="w200" v-model="listQuery.condition.endDate" type="datetime" placeholder="选择日期时间"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          align="right" ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" style="margin-left: 10px">查询</el-button>
          <el-button type="primary" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="clean:both"></div>
    <!--主列表-->
    <el-table ref="paymentTable" :data="tableData" v-loading="listLoading"
              element-loading-text="加载中" border fit highlight-current-row
              style="width: 100%;margin-top:5px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column align="center" label="id" v-if="false" width="0">
        <template slot-scope="scope">
          <span>{{scope.row.stockId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="序号" width="50" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>
      
      <el-table-column :key="key" align="center" :width="value.width" v-for='(value,key) in tableThead'
                       :label="value.title">
        <template slot-scope="scope">
          <div v-if="value.key === 'isShipment'">{{scope.row[value.key] | isShipmentFilter}}</div>
          <div v-else>{{scope.row[value.key]}}</div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.current" :page-sizes="[10,20,30,50]" :page-size="listQuery.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total">
      </el-pagination>
    </div>
    <!--出库面板-->
    <out-bound-edit
      :edit_flag2="outBoundFlag"
      :edit_main_title2="outBoundMainTitle"
      :edit_select_row="outBoundRowData"
      ref="outBoundEditRef"
      @edit-confirm="outBoundConfirm"
      @edit-close="outBoundClose"
    ></out-bound-edit>
    <!--库区调整面板-->
    <store-change-edit
      :edit_flag="storeChangeFlag"
      :edit_main_title="storeChangeMainTitle"
      :edit_select_row="storeChangeRowData"
      ref="storeChangeEditRef"
      @edit-confirm="storeChangeConfirm"
      @edit-close="storeChangeClose"
    ></store-Change-edit>
  </div>
</template>
<script>
  import * as FactoryPreparationAPI from '@/api/factoryPreparation/factoryPreparation'
  import waves from '@/directive/waves' // 水波纹指令
  import * as Utils from '@/utils/index'
  import { export_json_to_excel } from '@/vendor/Export2Excel'
  import OutBoundEdit from './fpInBoundConfig/outBoundEdit'
  import StoreChangeEdit from './preparationStockConfig/storeChangeEdit'
  const defautlTableThead = [
    { key: 'vin', title: '车架号', width: '180' },
    { key: 'storeHouseId', title: '仓库id', width: '120' },
    { key: 'isShipment', title: '是否有入库指令', width: '120' },
    { key: 'shipmentGid', title: '入库指令', width: '120' },
    { key: 'storeHouseName', title: '仓库名称', width: '120' },
    { key: 'targetStoreHouse', title: '目标仓库', width: '120' },
    { key: 'areaName', title: '库区', width: '120' },
    { key: 'locationNo', title: '库位', width: '120' },
    { key: 'qty', title: '库存量', width: '120' },
    { key: 'stockProperty', title: '库存属性', width: '120' },
    { key: 'inboundTime', title: '无单入库时间', width: '180' },
    { key: 'realInboundTime', title: '入库时间', width: '180' },
    { key: 'inboundUser', title: '无单入库用户', width: '180' },
    { key: 'gmtCreated', title: '创建时间', width: '' },
    { key: 'remark', title: '备注', width: '' }
  ]
  export default {
    name: 'stockQuery',
    components: { OutBoundEdit, StoreChangeEdit },
    directives: {
      waves
    },
    data() {
      return {
        theadCheckVal: [
          'vin',
          'storeHouseId',
          'locationNo',
          'prepareStatus',
          'materielId',
          'inboundUser',
          'inboundTime',
          'gmtCreated',
          'storeHouseName'
        ],
        tableThead: defautlTableThead,
        listQuery: {
          current: 1,
          size: 10,
          total: 0,
          condition: {
            vin: null,
            queryType: 'Y',
            isShipment: '',
            stockProperty: 'N',
            startDate: '',
            endDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59')
          }
        },
        tableData: [],
        listLoading: true,
        searchFlag: true,
        multipleSelection: [],
        tHeader: [], // excel头
        filterVal: [], // excel字段
        filename: '无单车库存列表', // excel表名
        outBoundFlag: false, // 出库面板 显示
        outBoundRowData: [], // 传入 出库面板 的当前列
        outBoundMainTitle: '', // 出库面板 标题
        storeChangeFlag: false, // 库区调整 显示
        storeChangeRowData: [], // 传入 库区调整 面板 的当前列
        storeChangeMainTitle: '', // 库区调整 面板 标题
        downloadLoading: false
      }
    },
    created() {
      this.getList()
      this.initFunc()
    },
    watch: {
      theadCheckVal(valArr) {
        this.tableThead = defautlTableThead.filter(v => {
          for (let i = 0; i < valArr.length; i++) {
            if (v.key === valArr[i]) {
              return v
            }
          }
        })
      }
    },
    methods: {
      initFunc() {
        this.tHeader = []
        this.filterVal = []
        defautlTableThead.map((item) => {
          this.tHeader.push(item.title)
          this.filterVal.push(item.key)
        })
      },
      changeStatus() {
        return this.downloadData.map(v => {
          if (v.prepareStatus === '10') {
            v.prepareStatus = '工厂备料入库'
          } else if (v.prepareStatus === '20') {
            v.prepareStatus = '移实顺'
          } else if (v.prepareStatus === '30') {
            v.prepareStatus = '提车指令出库'
          } else if (v.prepareStatus === '40') {
            v.prepareStatus = '返工厂'
          }
          if (v.isShipment === 'Y') {
            v.isShipment = '有'
          } else if (v.isShipment === 'N') {
            v.isShipment = '无'
          }
          return v
        })
      },
      exportExcel() {
        const that = this
        // 数据导出
        const queryParam = that.listQuery.condition
        queryParam.houseId = that.$store.getters.currentStorehouse.id
        queryParam.queryType = 'N'
        that.downloadLoading = true
        console.log('that.listQuery', queryParam)
        FactoryPreparationAPI.queryFactoryStock({ condition: queryParam }).then(result => {
          that.downloadLoading = false
          if (result.code === 0) {
            that.downloadData = result.data.records
            if (that.downloadData.length) {
              const arr = that.changeStatus()
              require.ensure([], () => {
                const data = that.formatJson(that.filterVal, arr)
                export_json_to_excel(that.tHeader, data, that.filename)
              })
            }
          } else {
            that.$message({
              title: '信息提示',
              message: result.message,
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      // 库区调整面板 打开
      editClickFunc() {
        if (this.checkSelect(this.multipleSelection) && this.checkSameStoreSelect(this.multipleSelection, 'storeHouseId', '仓库')) {
          if (this.multipleSelection.length === 1) {
            this.storeChangeMainTitle = '单个'
          } else {
            this.storeChangeMainTitle = '多个'
          }
          this.$refs.storeChangeEditRef.getHouseList(this.multipleSelection[0].storeHouseId)
          this.storeChangeRowData = this.multipleSelection
          this.storeChangeFlag = true
        }
      },
      storeChangeConfirm() {
        this.storeChangeFlag = false
        this.getList()
      },
      storeChangeClose() {
        this.storeChangeFlag = false
      },
      // 出库面板打开
      outClickFunc() {
        if (this.checkSelect(this.multipleSelection)) {
          this.outBoundMainTitle = '出库'
          this.outBoundRowData = this.multipleSelection
          this.outBoundFlag = true
        }
      },
      outBoundConfirm() {
        this.outBoundFlag = false
        this.getList()
      },
      outBoundClose() {
        this.outBoundFlag = false
      },
      // 列表查询
      getList() {
        this.listLoading = true
        // 处理是否展开更多
        let queryParam = {}
        if (this.searchFlag) {
          this.listQuery.condition.storeHouseId = this.$store.getters.currentStorehouse.id
          queryParam = this.listQuery
        } else {
          Object.assign(queryParam, this.listQuery)
          queryParam.condition = {
            startDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 00:00:00'),
            endDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59'),
            vin: this.listQuery.condition.vin,
            storeHouseId: this.$store.getters.currentStorehouse.id
          }
        }
        queryParam.condition.queryType = 'Y'
        FactoryPreparationAPI.queryFactoryStock(queryParam).then(result => {
          if (result.code === 0) {
            this.tableData = result.data.records
            this.listQuery.total = result.data.total
          } else {
            this.$message({
              title: '信息提示',
              message: result.message,
              type: 'error',
              duration: 2000
            })
          }
          this.listLoading = false
        })
      },
      // 更多
      moreSearch() {
        this.searchFlag = !this.searchFlag
      },
      // 查询
      search() {
        this.listQuery.current = 1
        this.listQuery.size = 10
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.listQuery.current = 1
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.current = val
        this.getList()
      },
      // 重置
      resetSearch() {
        this.listQuery.current = 1
        this.listQuery.size = 10
        this.listQuery.condition = {
          vin: null,
          queryType: 'Y',
          isShipment: '',
          stockProperty: 'Y',
          startDate: '',
          endDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59')
        }
        this.getList()
      },
      // 校验是否是 检查 同一仓库
      checkSameStoreSelect(arr, str, type) {
        if (arr.length > 1) {
          for (let c = 0; c + 1 < arr.length; c++) {
            // console.log('arr[c]', arr[c], 'arr[c + 1]', arr[c + 1])
            if (arr[c][str] !== arr[c + 1][str]) {
              // let val = arr[c][str]
              // if (str === 'billProperty') { val = payBillProperty(arr[c][str]) } // filter
              this.$message({
                message: '请选择是相同(' + type + ')的数据',
                type: 'warning',
                duration: 2000
              })
              return false
            }
          }
          return true
        }
        return true
      },
      // 检查是否选择单条
      checkSelect(data) {
        const l = data.length
        if (l === 0) {
          this.$message({
            message: '未选择',
            type: 'warning',
            duration: 2000
          })
          return false
        }
        return true
      },
      // 表格改变时
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

